#include <stdlib.h>
#include <iostream>

using std::cout;
using std::endl;

class Singleton
{
public:
    //在多线程情况下是不安全的
    static Singleton *getInstance()
    {
        if(nullptr == _pInstance)
        {
            atexit(destroy);
            _pInstance = new Singleton();//堆对象
        }

        return _pInstance;
    }

    static void destroy()
    {
        if(_pInstance)
        {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }
private:
    Singleton()
    {
        cout << "Singleton()" << endl;
    }

    ~Singleton()
    {
        cout << "~Singleton()" << endl;
    }

private:
    static Singleton *_pInstance;
};

/* Singleton *Singleton::_pInstance = nullptr;//饱汉模式（懒汉模式） */
Singleton *Singleton::_pInstance = getInstance();//饿汉模式

int main(int argc, char *argv[])
{
    Singleton::getInstance();
    Singleton::getInstance();
    Singleton::getInstance();
    return 0;
}

